﻿using BUGCOME.ServiceCore.Filters;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using MiniExcelLibs;

namespace BUGCOME.Common.Api.Controllers
{
    /// <summary>
    /// 多语言配置API控制器
    /// </summary>
    [Route("commonapi/[controller]/[action]")]
    [ApiController]
    [ApiExplorerSettings(GroupName = "common")]
    [Verify]
    public class LangController : BaseController
    {
        /// <summary>
        /// 多语言服务接口实例
        /// 用于封装多语言相关的业务逻辑处理，通过依赖注入获取具体实现
        /// </summary>
        private readonly ILangService _langService;

        /// <summary>
        /// 初始化LangController实例
        /// 通过依赖注入方式获取多语言服务实例，用于后续业务逻辑调用
        /// </summary>
        /// <param name="langService">多语言服务接口实现实例，提供多语言相关业务处理能力</param>
        public LangController(ILangService langService) => _langService = langService;

        /// <summary>
        /// 查询多语言配置列表（支持透视表）
        /// </summary>
        [HttpPost]
        [AllowAnonymous]
        [ActionPermissionFilter(Permission = "admin:lang:list")]
        public async Task<IActionResult> listLangByLocale([FromBody] LangQueryDto parm)
        {
            if (parm.ShowMode == 2)
            {
                return Success(new PagedInfo<dynamic>
                {
                    Result = await _langService.GetListToPivotAsync(parm)
                });
            }
            return Success(await _langService.GetListAsync(parm));
        }

        /// <summary>
        /// 按语言编码查询多语言配置（匿名访问）
        /// </summary>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> QueryLangs(string lang)
        {
            var msgList = await _langService.GetLangListAsync(new LangQueryDto { LangCode = lang });
            return Success(_langService.SetLang(msgList));
        }

        /// <summary>
        /// 按ID查询多语言配置详情
        /// </summary>
        [HttpPost]
        [ActionPermissionFilter(Permission = "admin:lang:query")]
        public async Task<IActionResult> GetLang(long Id)
        {
            var response = await _langService.GetFirstAsync(x => x.Id == Id);
            var list = await _langService.GetListAsync(x => x.LangKey == response.LangKey);
            return Success(new LangDto { LangKey = response.LangKey, LangList = list.Adapt<List<LangDto>>() });
        }

        /// <summary>
        /// 按语言键查询多语言配置详情
        /// </summary>
        [HttpPost]
        [ActionPermissionFilter(Permission = "admin:lang:query")]
        public async Task<IActionResult> GetLangByKey(string langKey)
        {
            var list = await _langService.GetListAsync(x => x.LangKey == langKey);
            return Success(new LangDto { LangKey = langKey, LangList = list.Adapt<List<LangDto>>() });
        }

        /// <summary>
        /// 更新多语言配置
        /// </summary>
        [HttpPost]
        [ActionPermissionFilter(Permission = "admin:lang:edit")]
        [Log(Title = "多语言配置", BusinessType = BusinessType.UPDATE)]
        public async Task<IActionResult> UpdateLang([FromBody] LangDto parm)
        {
            if (parm == null || parm.LangKey.IsEmpty())
                throw new CustomException("请求实体不能为空");
            await _langService.StorageLangAsync(parm);
            return ToResponse(1);
        }

        /// <summary>
        /// 按ID批量删除多语言配置
        /// </summary>
        [HttpPost]
        [ActionPermissionFilter(Permission = "admin:lang:delete")]
        [Log(Title = "多语言配置", BusinessType = BusinessType.DELETE)]
        public async Task<IActionResult> DeleteLang(string ids)
        {
            var idsArr = Tools.SpitLongArrary(ids);
            if (idsArr.Length <= 0)
                return ToResponse(ApiResult.Error("删除失败Id 不能为空"));
            return ToResponse(await _langService.DeleteAsync(idsArr));
        }

        /// <summary>
        /// 按语言键删除多语言配置
        /// </summary>
        [HttpPost]
        [ActionPermissionFilter(Permission = "admin:lang:delete")]
        [Log(Title = "多语言配置", BusinessType = BusinessType.DELETE)]
        public async Task<IActionResult> DeleteLangByKey(string langkey)
        {
            if (langkey.IsEmpty())
                return ToResponse(ApiResult.Error("删除失败Id 不能为空"));
            var response = await _langService
                .Deleteable()
                .EnableDiffLogEvent()
                .Where(f => f.LangKey == langkey)
                .ExecuteCommandAsync();
            return ToResponse(response);
        }

        /// <summary>
        /// 导出多语言配置
        /// </summary>
        [Log(Title = "多语言配置", BusinessType = BusinessType.EXPORT, IsSaveResponseData = false)]
        [HttpPost]
        [ActionPermissionFilter(Permission = "admin:lang:export")]
        public async Task<IActionResult> Export([FromQuery] LangQueryDto parm)
        {
            parm.PageSize = 10000;
            var list = await _langService.GetListToPivotAsync(parm);
            string sFileName = ExportExcel(list, "Lang", "多语言配置");
            return Success(new { path = $"/export/{sFileName}", fileName = sFileName });
        }

        /// <summary>
        /// 导入多语言配置
        /// </summary>
        /// <param name="formFile">上传的Excel文件</param>
        /// <returns>导入结果</returns>
        [HttpPost]
        [Log(Title = "多语言设置导入", BusinessType = BusinessType.IMPORT, IsSaveRequestData = false, IsSaveResponseData = true)]
        [ActionPermissionFilter(Permission = "admin:lang:import")]
        public async Task<IActionResult> ImportData(IFormFile formFile)
        {
            var list = new List<Lang>();
            var nowTime = DateTime.Now;
            using (var stream = formFile.OpenReadStream())
            {
                foreach (var item in stream.Query(startCell: "A2").ToList())
                {
                    list.Add(new Lang { LangCode = "zh-cn", LangKey = item.A, LangName = item.B, Addtime = nowTime });
                    list.Add(new Lang { LangCode = "en", LangKey = item.A, LangName = item.C, Addtime = nowTime });
                    list.Add(new Lang { LangCode = "zh-tw", LangKey = item.A, LangName = item.D, Addtime = nowTime });
                }
            }
            return Success(await _langService.ImportLangAsync(list));
        }

        /// <summary>
        /// 下载多语言设置导入模板
        /// </summary>
        [HttpPost]
        [Log(Title = "多语言设置模板", BusinessType = BusinessType.EXPORT, IsSaveRequestData = true, IsSaveResponseData = false)]
        [AllowAnonymous]
        public async Task<IActionResult> ImportTemplateExcel()
        {
            var result = await Task.Run(() => DownloadImportTemplate(new List<Lang>(), "lang"));
            return ExportExcel(result.Item2, result.Item1);
        }
    }
}
